using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data.Objects;
using Locator.Common.DataAccess.Interface;
using Locator.Common.Model;

namespace Locator.Common.DataAccess
{
    public class SqlUnitOfWork : IUnitOfWork
    {

        public SqlUnitOfWork()
        {
            var connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
            this.context = new ObjectContext(connectionString);
            context.ContextOptions.LazyLoadingEnabled = true;
        }

        public IRepository<Store> Stores
        {
            get
            {
                if (this.stores == null)
                {
                    this.stores = new SqlRepository<Store>(this.context);
                }

                return stores;
            }
        }

        public IRepository<User> Users
        {
            get
            {
                if (this.users == null)
                {
                    this.users = new SqlRepository<User>(this.context);
                }

                return users;
            }
        }

        public void Commit()
        {
            this.context.SaveChanges();
        }

        private readonly ObjectContext context;
        private SqlRepository<Store> stores;
        private SqlRepository<User> users;
        private const string ConnectionStringName = "LcboDrinkLocatorEntities";
        private bool disposed;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~SqlUnitOfWork()
        {
            this.Dispose(false);
        }
    }
}
